﻿using System;
using System.Windows;

namespace ZOIL.DataBackend.Server
{
    /// <summary>
    /// Interaction logic for ServerGUI.xaml
    /// </summary>
    public partial class ServerGUI : Window
    {
        
        public ServerGUI()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(Window1_Loaded);
            Closed += new EventHandler(Window1_Closed);
            Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing);
        }

        /// <summary>
        /// Event Handler for the Window closing Event. This occurs just before the window gets closed and enables Canceling of the window closing
        /// we use it to ensure that all databases are stopped
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Server s = Server.getInstance();
            foreach (DatabaseConfiguration config in s.Databases)
            {
                if (config.Status == DatabaseStatus.Running)
                {
                    e.Cancel = true;
                    MessageBox.Show("Please stop all running databases, before closing.");
                    break;
                }
            }
        }

        /// <summary>
        /// Event Handler for the Window Closed Event.
        /// We save all Databases to the config container and close the config container
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Window1_Closed(object sender, EventArgs e)
        {
            Server s = Server.getInstance();
            s.SaveConfig();
            s.CloseConfigContainer();
        }

        /// <summary>
        /// Event Handler for the Window Loaded Event.
        /// We use it to bind the MVVM Parts together
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            Server s = Server.getInstance();
            ServerViewModel svm = new ServerViewModel();
            svm.Model = s;
            RootWindow.DataContext = svm;
        }
    }
}
